package cn.taobaoke.restful.service;

import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.util.GsonUtil;
import cn.taobaoke.restful.util.MD5Util;
import cn.taobaoke.restful.util.OkHttpUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * TaobaoService类.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: TaobaoApi                                                                         |
 * |创建时间: 4/23/17                                                                               |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 *
 * @author luch
 */
@Service
public class TaobaoApi {

    private static Logger logger = LogManager.getLogger(TaobaoApi.class);

    //    阿里云服务
//    private static final String TKL_URL = "http://112.74.39.9:6988/api/tkl";
//    聚石塔服务
    private static final String TKL_URL = "http://118.178.98.86:80/api/tkl";

    public static String getTaokoulin(String couponUrl, String domain) {
        return getTaokoulin(couponUrl, null, domain);
    }

    public static String getTaokoulinByCouponAndPid(String domain, String couponUrl, String pid) {
        // replace pid with new pid
        // pid=mm_14679296_14892152_57994304
        int left = couponUrl.indexOf("pid=");
        int right = -1;
        if (left > 0) {
            right = couponUrl.indexOf("&", left);
            if (right > 0) {
                couponUrl = couponUrl.substring(0, left + 4) + pid + couponUrl.substring(right);
            } else {
                couponUrl = couponUrl.substring(0, left + 4) + pid;
            }
        } else {
            couponUrl = couponUrl + "&pid=" + pid;
        }
        // link += "&pid=" + pid;

        logger.info("taobaoApi.getTaokoulin: Link={}", couponUrl);
        return getTaokoulin(couponUrl, domain);
    }

    public static String getTaokoulin(String couponUrl, String text, String domain) {
        if (text == null) {
            text = "超值优惠券";
        }

        logger.info("couponUrl => {} text => {}", couponUrl, text);

        Map<String, Object> params = new HashMap<>();
        params.put("url", couponUrl);
        params.put("text", text);
        params.put("domain", domain);

        try {
            String jsonRet = OkHttpUtil.DEFAULT.postJson(TKL_URL, GsonUtil.getJsonString(params));
            logger.info("request taokoulin: {}, param: {}, response: {}", TKL_URL, params, jsonRet);
            Map<String, Object> map = GsonUtil.getObject(jsonRet);
            if (map != null && map.containsKey("data")) {
                String tkl = (String) map.get("data");
//                if (tkl.contains("《")) {
//                    tkl = tkl.replace("《", "¥");
//                }
                return tkl;
            }
        } catch (IOException e) {
            logger.error("生成淘口令出错!", e);
        }

        return null;
    }


    public static Map tranlateTaokoulinToPid(String taokoulin, String pid, String domain) throws IOException {
//        String couponUrl = parseTaokoulin(taokoulin);
        String couponUrl = null;
        try {
            couponUrl = parseTaokoulinFromWinServer(taokoulin);
        } catch (Exception e) {
            logger.error("解析淘口令错误", e);
            throw new TBKException("解析淘口令失败");
        }
        if (couponUrl == null) {
            throw new TBKException("解析淘口令失败");
        }
        logger.info("coupon url => {}", couponUrl);

        // activityId = ,
        String couponActivity = null;
        int idx = couponUrl.indexOf("activityId");
        if (idx <= 0) {
            logger.error("解析淘口令的优惠券地址失败,缺少activityId参数, taokoulin: {}, couponUrl: {}", taokoulin, couponUrl);
            throw new TBKException("解析淘口令失败");
        }
        int lastIdx = couponUrl.indexOf("&", idx + 10);
        if (lastIdx > 0) {
            couponActivity = couponUrl.substring(idx + 11, lastIdx);
        } else {
            couponActivity = couponUrl.substring(idx + 11);
        }
        String couponDetailUrl = couponUrl.replace("/coupon/edetail", "/cp/coupon");
        String detailJson = OkHttpUtil.DEFAULT.get(couponDetailUrl);

        logger.info("request coupon detail: {}, response detail json: {}", couponDetailUrl, detailJson);


        Map detailMap = GsonUtil.getObject(detailJson);
        if (detailMap == null) throw new TBKException("获取优惠券信息失败");
        Boolean success = (Boolean) detailMap.get("success");
        if (success == null || !success) {
            logger.error("获取优惠券信息失败, Request: {}, Response: {}", couponDetailUrl, detailJson);
            throw new TBKException((String) detailMap.get("message"));
        }
        Map couponMap = (Map) detailMap.get("result");

        Map retMap = new HashMap();
        retMap.put("couponActivity", couponActivity);
        retMap.put("couponAmount", couponMap.get("amount"));
        retMap.put("couponFee", couponMap.get("startFee"));
        retMap.put("couponStart", couponMap.get("effectiveStartTime"));
        retMap.put("couponEnd", couponMap.get("effectiveEndTime"));
        retMap.put("shopName", couponMap.get("shopName"));
        retMap.put("shopUrl", couponMap.get("shopUrl"));
        if (retMap.containsKey("shopLogo")) {
            retMap.put("shopUrl", "https:" + couponMap.get("shopLogo"));
        }
        Map itemMap = (Map) couponMap.get("item");

        String itemId = null;
        String dx = null;
        if (itemMap != null) {
            if (itemMap.containsKey("clickUrl")) {
                retMap.put("clickUrl", "https:" + itemMap.get("clickUrl"));
            }
            if (itemMap.containsKey("picUrl")) {
                retMap.put("itemImage", "https:" + itemMap.get("picUrl"));
            }
            retMap.put("itemName", itemMap.get("title"));
            if (itemMap.containsKey("discountPrice")) {
                retMap.put("itemPrice", itemMap.get("discountPrice"));
            } else if (itemMap.containsKey("reservePrice")) {
                retMap.put("itemPrice", itemMap.get("reservePrice"));
            }
            itemId = ((Double) itemMap.get("itemId")).longValue() + "";
            retMap.put("itemId", itemMap.get("itemId"));
            if (itemMap.containsKey("tmall")) {
                String tmall = (String) itemMap.get("tmall");
                // 是否天猫的 0-淘宝, 1-天猫
                if (tmall.equals("0")) {
                    // 将 0 改为 2
                    dx = "2";
                    retMap.put("shopType", "2");
                } else {
                    dx = "0";
                    retMap.put("shopType", tmall); // 是否天猫的 0-淘宝, 1-天猫
                }
            }
        }
        //        itemId
        String couponLink = "https://uland.taobao.com/coupon/edetail?activityId=" + couponActivity + "&itemId=" + itemId + "&src=jgmh_wsmh&pid=" + pid + "&dx=" + dx;
        retMap.put("couponLink", couponLink);
        String newTkl = getTaokoulin(couponLink, "超值优惠", domain);
        retMap.put("taokoulin", newTkl);
        return retMap;
    }


    public static String parseTaokoulinFromWinServer(String token) throws IOException {
        // 解析淘口令服务挂在 腾讯云 win server 2012 上的
        String url = String.format("http://123.207.243.24/tb/api/parseTkl?tkl=%s", token);


        String jsonRet = OkHttpUtil.DEFAULT.get(url);
        logger.info("request: {}, response: {}", url, jsonRet);

        Map retMap = GsonUtil.getObject(jsonRet);
        Boolean success = (Boolean) retMap.get("success");
        if (success != null && success) {
            return (String) retMap.get("data");
        }
        return null;
    }


    /**
     * 解析淘口令,
     *
     * @param token
     * @return
     */
    public static String parseTaokoulin(String token) {
        String data = String.format("{\"passwordType\":\"tao\",\"passwordText\":\"%s\"}", token);
        String sign = MD5Util.md5(data);
        String signs = "744e7d7e7028b817bd9f8f3c6f28a8d3&a171b739a2168bd9c188cf15f9139f90&mtop.taobao.wireless.share.password.get&1.0&0&0&" + sign + "&0";

        signs = MD5Util.md5(signs);
        String url = "http://api.m.taobao.com/rest/api3.do?";
        url = url + "api=mtop.taobao.wireless.share.password.get";
        url = url + "&v=1.0&imei=0&imsi=0&ttid=0&t=0";
        url = url + "&t=0&appKey=12278902&data=%7B%22passwordType%22%3A%22tao%22%2C%22passwordText%22%3A%22";
        url = url + token + "%22%7D&sign=" + signs;

        try {
            String json = OkHttpUtil.DEFAULT.get(url);
            logger.info("Get Taokoulin => {}, Request: {}, Response: {}", token, url, json);

            Map map = GsonUtil.getObject(json);
            if (map.containsKey("data")) {
                Map dataMap = (Map) map.get("data");
                if (dataMap != null && dataMap.containsKey("url")) {
                    String couponUrl = (String) dataMap.get("url");
                    return couponUrl;
                }
            }
            return null;
        } catch (IOException e) {
            logger.info("Get Taokoulin => {}, Request: {}", token, url);
            logger.error("解析淘口令出错!", e);
        } catch (Exception e) {
            logger.info("Get Taokoulin => {}, Request: {}", token, url);
            logger.error("解析淘口令出错!", e);
        }
        return null;
    }


}
